package com.adong.dao.impl;

import com.adong.dao.UserDao;
import com.adong.domain.User;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author com.adong
 */
public class UserDaoImpl implements UserDao {

    JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<User> finAll() {
        String sql = "SELECT id,username,Email,PASSWORD,phoneNum FROM sys_user";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
    }

    @Override
    public long save(User user) {

        PreparedStatementCreator creator = new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                //使用原始的jdbc完成PreparedStatement组建
                String sql = "insert into sys_user values(?,?,?,?,?)";
                PreparedStatement preparedStatement = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setObject(2,user.getUsername());
                preparedStatement.setObject(3,user.getEmail());
                preparedStatement.setObject(4,user.getPassword());
                preparedStatement.setObject(5,user.getPhoneNum());
                return preparedStatement;
            }
        };
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        //获取的生成的组件
        jdbcTemplate.update(creator,keyHolder);
        long userId = keyHolder.getKey().longValue();
        return userId;
    }

    @Override
    public void saveUSerRole(Long userId, long[] roleIds) {
        for(long roleId:roleIds){
            jdbcTemplate.update("insert into `sys_user_role` values(?,?)",userId,roleId);
        }
    }

    @Override
    public void delUserRole(long userId) {
        String sql = "DELETE  FROM sys_user_role WHERE userId = ?" ;
        jdbcTemplate.update(sql,userId);
    }

    @Override
    public void del(long userId) {
        String sql ="delete from sys_user where id = ?" ;
        jdbcTemplate.update(sql,userId);

    }


}
